<?php
namespace common\models;




class Member extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'member';
    }


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['out_mid', 'invite_id', 'grade', 'm_grade', 'user_type', 'create_time', 'update_time'], 'integer'],
            [['balance_due'], 'number'],
            [['member_name', 'address'], 'string', 'max' => 64],
            [['member_mobile'], 'string', 'max' => 13],
            [['member_email', 'private_key', 'member_avatar'], 'string', 'max' => 128],
            [['loginpwd', 'paypwd', 'auth_key'], 'string', 'max' => 32],
            [['state'], 'string', 'max' => 1],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'member_id' => 'Member ID',
            'out_mid' => '外部会员id',
            'member_name' => '会员姓名',
            'member_mobile' => '会员电话',
            'member_email' => '邮箱',
            'invite_id' => '推荐人',
            'grade' => '用户等级',
            'm_grade' => '投资等级',
            'user_type' => '1普通用户 2空单用户',
            'loginpwd' => '登录密码',
            'paypwd' => '支付密码',
            'auth_key' => '会员令牌',
            'address' => '钱包地址',
            'private_key' => '私钥',
            'member_avatar' => '用户头像',
            'state' => '用户状态 1正常 0冻结',
            'balance_due' => '欠款',
            'create_time' => '创建时间',
            'update_time' => '更新时间',
        ];
    }    

	/*
		* 数据列表
		* whereArr 条件
		* params 基本参数 包含 field order page limit
		* extends  扩展信息 一些相关的信息
		* 
	*/	
	public static function dataList($whereArr, $params, $extends = array())
	{
		$model  = self::find();
		$where  = isset($whereArr['where']) ? $whereArr['where'] : [];
		$whereAnd = isset($whereArr['and'])?$whereArr['and']:[];
		$models = self::queryFormart($model,$where,$params,$whereAnd);
		$model  = $models['model'];
		
		$data  = $model->asarray()->all();
		if(!$data) return array();

		//扩展信息
		if(!$extends) return $data;

		foreach($extends as $extend)
		{

		}

		return $data;	
	}

	public static function getOne($where, $field = ['*'])
	{
		return self::find()->select($field)->where($where)->asarray()->one();
	}


	public static function getAll($where = [], $field = ['*'])
	{
		return self::find()->select($field)->where($where)->asarray()->all();
	}

    /*
    会员列表显示
    * whereArr 条件
    * params 基本参数 包含 field order page limit
    * extends  扩展信息 一些相关的信息
*/
    public static function MemberList($whereArr,$params,$extends=array())
    {

        $model  = self::find();
        $where  = $whereArr['where'];
        $whereAnd = isset($whereArr['whereAnd'])?$whereArr['whereAnd']:[];
        $models = self::queryFormart($model,$where,$params,$whereAnd);
        $model  = $models['model'];
        self::$pages = $models['pages'];

        $data  = $model->asarray()->all();
        if(!$data) return array();
        //扩展信息
        if(!$extends) return $data;

        foreach($data as &$member)
        {
            foreach($extends as $val)
            {
                if($val=='inviter') //推荐人
                {
                    $inviter = self::getMemberById($member['invite_id']);
                    if($inviter)
                        $member['inviter'] = $inviter['member_name'].'/'.$inviter['member_id'];
                    else
                        $member['inviter'] = '无';

                }else if($val=='team_total')  //团队业绩
                {
                    $teamData = TeamTotal::getTeamTotal($member['member_id']);
                    $member['my_total'] = $teamData?$teamData['my_total']:0;
                    $member['team_total'] = $teamData?$teamData['team_total']:0;
                }elseif($val=='group'){
                    $member['fina_count']=GroupFinalist::find()->where(['member_id'=>$member['member_id']])->count();
                    $member['winning_count']=GroupWinning::find()->where(['member_id'=>$member['member_id']])->count();
                }elseif($val=='order'){
                    $member['order_count']=StaticInstance::find()->where(['member_id'=>$member['member_id']])->count();
                }
                $income = Balance::getOne(['member_id'=>$member['member_id'],'balance_type'=>4]);
                $member['income'] =$income['balance'];
                $contract = Balance::getOne(['member_id'=>$member['member_id'],'balance_type'=>3]);
                $member['contract'] =$contract['balance'];
                 $money = Balance::getOne(['member_id'=>$member['member_id'],'balance_type'=>1]);
                $member['money'] =$money['balance'];
            }

        }

        return $data;
    }

    public static  function groupMember($whereArr,$params,$extends=array()){
        $model  = self::find();
        $where  = $whereArr['where'];
        $whereAnd = isset($whereArr['whereAnd'])?$whereArr['whereAnd']:[];

        $group_data = GroupDetail::getOne(['group_detail_id'=>$params['group_detail_id']],
            'group_detail_id,member_id,finalist_id,winning_id');

       /*参与*/
        if ($params['group_type']==1){
            $memberArr   = explode(',',$group_data['member_id']);
            $winningArr=[];
            $finalistArr=[];
            if ($group_data['winning_id']) {
                $winningArr = explode(',',$group_data['winning_id']);
            }

            if ($group_data['finalist_id']){
                $finalistArr=explode(',',$group_data['finalist_id']);
            }

            if ($params['type']==1){
                $idArr       = array_diff($memberArr,$finalistArr);
                $id_arr      = array_diff($idArr,$winningArr);
            }else {
                $id_arr      = array_diff($memberArr,$winningArr);
            }

        }elseif ($params['group_type']==2){
            $id_arr = explode(',',$group_data['finalist_id']);
        }else {

            $id_arr = explode(',',$group_data['winning_id']);


        }
        $where['member_id']=$id_arr;
        $models = self::queryFormart($model,$where,$params,$whereAnd);
        $model  = $models['model'];
        self::$pages = $models['pages'];
        $data  = $model->asarray()->all();

        if(!$data) return array();
        //扩展信息
        if(!$extends) return $data;


        foreach($data as &$member)
        {
            foreach($extends as $val)
            {
                if ($val=='winning_id'){
                    $winning = GroupWinning::getOne(['member_id'=>$member['member_id'],
                        'group_detail_id'=>$params['group_detail_id']],'is_order,winning_time');
                    $member['is_order'] = $winning['is_order']==1?'是':'否';
                    $member['winning_time'] = $winning['winning_time'];
                    $finalist = GroupFinalist::getAll(['member_id'=>$member['member_id'],
                        'group_detail_id'=>$params['group_detail_id']],'finalist_time');
                    $member['finalist_time']='';
                    $fina=[];
                    if ($finalist) {
                        foreach ($finalist as $k => $v) {
                            $fina[]=$v['finalist_time'];
                        }
                        $member['finalist_time'] = implode(',',$fina);
                        $member['ruwei_count']   = count($finalist);
                    }
                }
            }

        }
        return $data;
    }
    /*
    删除会员
    member_id
*/
    public static function MemberDel($memberId)
    {
        $where = ['member_id'=>$memberId];
        $res   = self::deleteAll($where);
        return $res;
    }

        /*
        通过id获取用户
    */
    public static function getMemberById($memberId,$field=['*'])
    {
        if(!$memberId) return false;
        return self::find()->select($field)->where(['member_id' => $memberId])->asarray()->one();
        return self::findOne(['member_id' => $memberId]);
    }

        /*
        通过id 或是 电话等信息查询用户
     */
        public static function queryMember($memberKey,$field)
        {
            if(!$memberKey) return false;
            $where = ['or','member_id='.$memberKey,'member_mobile="'.$memberKey.'"'];
            return self::find()->select($field)->where($where)->asarray()->one();
        }

    //生成auth_key
    public static function generateAuthKey()
    {
            return \Yii::$app->security->generateRandomString();

    }
}